<!-- 图片视频上传 -->
<template>
	<view @click.prevent="onClick">
		<u-upload
			:fileList="fileList1"
			@afterRead="afterRead"
			@delete="deletePic"
			@beforeRead="beforeRead"
			:useBeforeRead="true"
			name="1"
			:multiple="multiple"
			:maxCount="10"
		></u-upload>
		<!-- 权限告知弹窗 -->
		<yk-authpup ref="authpup" type="top" @changeAuth="changeAuth" :permissionID="permissionID"></yk-authpup>
	</view>
</template>

<script>
	import ykAuthpup from "@/components/yk-authpup/yk-authpup";
	import { BASE_URL } from '@/utils/baseUrl.js'
	import { imageUrl } from '@/utils/common.js'
	export default {
		name: "uploadImage",
		data() {
			return {
				fileList1: [],
				permissionID: 'CAMERA',
			}
		},
		components: {
			ykAuthpup
		},
		model: {
		  prop: 'fileList',
		  event: 'change',
		},
		props: {
			multiple: {
				type: Boolean,
				default: true
			},
			disabled: {
				type: Boolean,
				default: false
			},
			// 文件字符串，多个用逗号隔开
			fileList: {
			  type: [String, Array],
			  require: true,
			},
		},
		
		watch: {
		  fileList: {
		    handler(val) {
		      if (val) {
		        // 判断是否为数组
		        var fileListArr = ''
		        if (Array.isArray(val)) {
		          // 当是数组时
		          fileListArr = []
		          val.map((value) => {
		            fileListArr.push({
		          		url: imageUrl(value.filePath)
		          	})
		          })
		        } else {
		          // 不是数组时
		          var arrImage = val.split(',')
							fileListArr = []
							arrImage.map((value) => {
							  fileListArr.push({
									url: imageUrl(value)
								})
							})
		        }
						this.fileList1 = fileListArr
		      } else {
		        this.fileList1 = []
		      }
		    },
		    immediate: true,
		  },
		},
		methods:{
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
				const str = this[`fileList${event.name}`].map(obj => {
					let index = obj.url.indexOf("static/");
					let result = ''
					if (index !== -1) {
						result = obj.url.substr(index + 7, obj.url.length); 
					} else {
						result = obj.url
					}
					return result
				}).join(',');
				this.$emit('change', str)
			},
			beforeRead (event) {
			},
			onClick () {
				this.openAuth()
			},
			openAuth(){
				this.$refs['authpup'].open() //调起自定义权限目的弹框,具体可看示例里面很详细
			},
			changeAuth () {
				
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
					const str = this[`fileList${event.name}`].map(obj => {
						let index = obj.url.indexOf("static/");
						let result = ''
						if (index !== -1) {
							result = obj.url.substr(index + 7, obj.url.length); 
						} else {
							result = obj.url
						}
						return result
					}).join(',');
					this.$emit('change', str)
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: BASE_URL + '/api/erpmng/sys/common/upload', // 上传图片接口
						filePath: url,
						name: 'file',
						header: {
							'Authorization': uni.getStorageSync('ACCESS_TOKEN'),
							'client-id': 'app_erp',
							'user-id': uni.getStorageSync('userInfo').id
						},
						formData: {
							biz: 'temp'
						},
						success: (res) => {
							var data = JSON.parse(res.data)
							resolve(data.result)
						}
					});
				})
			},
		}

	}
</script>